#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tmf_http.py 
@version:
@time: 2022/03/01 
"""
from TapClientCore.T02_tm_api.v2_api.v2_tm import v2tm
from TapClientCore.T03_api_body_templates.v2_api_body import DATASOURCE_HTTP_CUSTOM
from TapClientCore.T03_api_body_templates.v2_api_body import DATASOURCE_HTTP_MQ
from TapClientCore.T03_api_body_templates.v2_api_body import DATASOURCE_HTTP_KAFKA
from TapException.TM import *


class TMFHttp:
    """
    TM Feature for Http DataSource
    """

    @staticmethod
    def create_data_source(conf):
        tmp = None
        if conf.get('database_type') == 'kafka':
            tmp = DATASOURCE_HTTP_KAFKA.copy()
            tmp.update(conf)
        elif conf.get('database_type') == 'mq':
            tmp = DATASOURCE_HTTP_MQ.copy()
            tmp.update(conf)
        else:
            tmp = DATASOURCE_HTTP_CUSTOM.copy()
            tmp.update(conf)
        return v2tm.post_connections(tmp).get('data')

    @staticmethod
    def delete_data_source_by_id(connection_id):
        return v2tm.delete_connections_by_id(connection_id)

    @staticmethod
    def patch_data_source_by_id(connection_id, update_conf):
        return v2tm.patch_connections_by_id(connection_id, update_conf)

    @staticmethod
    def get_all_data_source():
        return v2tm.get_connections()

    @staticmethod
    def get_data_source_by_id(connection_id):
        return v2tm.get_connections_by_id(connection_id)

    @staticmethod
    def post_datasource_copy_by_name(connection_id, name):
        payload = {"uri": f"{connection_id}/copy", "headers": {"lconname-name": f"{name}"}}
        return v2tm.post_connections_copy_by_id(connection_id, payload)

    # ----- OPERATE DATASOURCE BY NAME ------

    def get_data_source_by_name(self, connection_name):
        """
        通过数据源名字获取数据源信息
        :param connection_name:
        :return:
        """
        response = self.get_all_data_source()
        datasource_list = response.get('data').get('items')
        for one_datasource in datasource_list:
            if connection_name == one_datasource.get('name'):
                return one_datasource
        from TapUtil.logfunc.logger import logger
        logger.fatal(f'{connection_name} not found')
        raise TapdataNoThisDataSource

    def delete_data_source_by_name(self, name):
        """
        通过数据源名称删除数据源
        :param name:
        :return:
        """
        response = self.get_data_source_by_name(name)
        connection_id = response.get('id')
        delete_response = self.delete_data_source_by_id(connection_id)
        return delete_response

    def patch_data_source_by_name(self, name, payload):
        """
        通过数据源名称修改数据源
        :param name:
        :param payload:
        :return:
        """
        response = self.get_data_source_by_name(name)
        connection_id = response.get('id')
        patch_result = self.patch_data_source_by_id(connection_id, payload)
        return patch_result

    def copy_datasource_by_name(self, name):
        response = self.get_data_source_by_name(name)
        connection_id = response.get('id')
        copy_result = self.post_datasource_copy_by_name(connection_id, name)
        return copy_result.get('data')

    def _http_loading_schema_by_name(self, name):
        """
        通过数据源名称加载schema http
        :param name:
        :return:
        """
        response = self.get_data_source_by_name(name)
        connection_id = response.get('id')
        patch_payload = {"loadCount": 0, "loadFieldsStatus": "loading"}
        patch_result = self.patch_data_source_by_id(connection_id, patch_payload)
        return patch_result

    def ws_loading_schema_by_name(self, name):
        """
        通过数据源名称加载schema ws
        :param name:
        :return:
        """
        response = self.get_data_source_by_name(name)
        datasource_info = response
        from .tmf_ws import ws_load_schema
        ws_result = ws_load_schema(v2tm.ws_uri, datasource_info)
        if not ws_result:
            raise LoadSchemaError
        return ws_result

    def _try_link_by_name(self, name):
        """
        数据源连接测试
        :param name:
        :return:
        """
        response = self.get_data_source_by_name(name)
        connection_id = response.get('id')
        patch_payload = {"status": "testing"}
        self.patch_data_source_by_id(connection_id, patch_payload)
        return connection_id

    def test_datasource_by_name(self, name):
        """
        通过数据源名加载schema
        :param name:
        :return:
        """
        self._try_link_by_name(name)
        self._http_loading_schema_by_name(name)
        self.ws_loading_schema_by_name(name)
